package com.leyou.item.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.leyou.item.dto.CategoryDTO;
import com.leyou.item.entity.Category;
import com.leyou.item.entity.CategoryBrand;
import com.leyou.item.mapper.CategoryMapper;
import com.leyou.item.service.CategoryBrandService;
import com.leyou.item.service.CategoryService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;

import java.util.Collection;
import java.util.Collections;
import java.util.List;
import java.util.stream.Collectors;

@Service
public class CategoryServiceImpl extends ServiceImpl<CategoryMapper, Category> implements CategoryService {
    @Autowired
    private CategoryBrandService categoryBrandService;

    @Override
    public List<CategoryDTO> queryCategoryByPid(Long pid) {
        List<Category> categoryList = query().eq("parent_id", pid).list();
        List<CategoryDTO> categoryDTOS = CategoryDTO.convertEntityList(categoryList);
        return categoryDTOS;
    }

    @Override
    public CategoryDTO queryCategoryById(Integer id) {
        CategoryDTO categoryDTO = new CategoryDTO(getById(id));
        return categoryDTO;
    }

    @Override
    public List<CategoryDTO> queryCategoryByIds(List<Long> ids) {
        List<Category> categories = listByIds(ids);
        return CategoryDTO.convertEntityList(categories);
    }

    @Override
    @Transactional
    public List<CategoryDTO> queryCategoryByBrandId(Long brandId) {
        List<Long> ids = baseMapper.getCategoryIdsByBrandId(brandId);
        if(CollectionUtils.isEmpty(ids)){
            return Collections.emptyList();
        }

        List<CategoryBrand> categoryBrands = categoryBrandService.query()
                .eq("brand_id", brandId).list();
        List<Long> list = categoryBrands.stream().map(CategoryBrand::getCategoryId)
                .collect(Collectors.toList());
        if(CollectionUtils.isEmpty(list)){
            return Collections.emptyList();
        }

        List<Category> categories = listByIds(ids);
        return CategoryDTO.convertEntityList(categories);
    }
}
